package com.liu.notice.base;

import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * @Author Liu Ke
 * @Date 2020/8/1  16:30
 * @Description 参数格式校验
 * @Version 1.0
 */
@SuppressWarnings("JavaDoc")
public class ServiceParent {
	@Value("${preStylePath}")
	private String preStylePath;
	/**
	 * 入参格式校验
	 * @param map
	 * @param transName
	 */
	public void styleCheck(Map<String, String> map, String transName) throws Exception {
		StringBuffer fileName = new StringBuffer().append(preStylePath)
				.append(transName).append(".properties");
		Properties properties = new Properties();
		InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName.toString());

		try {
			properties.load(in);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//遍历Map进行格式校验
		Iterator entries = map.entrySet().iterator();
		while (entries.hasNext()) {
			Map.Entry entry = (Map.Entry) entries.next();
			String key = (String) entry.getKey();
			Object value = entry.getValue();

			String notNull = new StringBuffer().append(key).append(".notNull").toString();
			String maxLength = new StringBuffer().append(key).append(".maxLength").toString();
			String regex = new StringBuffer().append(key).append(".regex").toString();

			//1、非空校验
			String notNullFlag = properties.getProperty(notNull);
			if ("true".equals(notNullFlag) && isNullOrEmpty(value)) {
				throw new Exception("<"+transName+"> Parameter non null verification failed,["+key+"] Cannot be null");
			}
			//2、String类型长度校验
			String lengthString = properties.getProperty(maxLength);
			if (!isNullOrEmpty(lengthString)) {
				int length = Integer.parseInt(lengthString);
				if (value instanceof String && ((String) value).length() > length) {
					throw new Exception("<"+transName+"> Parameter length verification failed,["+key+"] maxLength="+length);
				}
			}
			//3、正则校验(String)
			String regRule = properties.getProperty(regex);
			if (!isNullOrEmpty(regRule) && Pattern.matches(regRule,(String)value)) {
				throw new Exception("<"+transName+"> Parameter regular verification failed,["+key+"] regex="+regRule);
			}
		}
	}
	private boolean isNullOrEmpty(Object value){
		return "".equals(value) || value == null;
	}

}
